package com.elaticsearch.doc;

import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;

import java.io.IOException;

/**
 * @author:左泽林
 * @date:日期:2021-08-28-时间:16:13
 * @message:
 */
public class doc_Insert_Batch {
    public static void main(String[] args) throws IOException {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("172.20.17.43",9200,"http"))
        );

        try {
           //批量插入数据
            BulkRequest bulkRequest = new BulkRequest();

            //概念：多个请求包装起来一起发送。
            bulkRequest.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON,"name","zhangshan","age",30,"sex","男"));
            bulkRequest.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON,"name","Lisi","age",30,"sex","女"));
            bulkRequest.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON,"name","Wangwu","age",40,"sex","男"));
            bulkRequest.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON,"name","Wangwu2","age",50,"sex","女"));
            bulkRequest.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON,"name","Wangwu3","age",60,"sex","男"));

            BulkResponse response = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);

            System.out.println("===============操作结果==============");
            System.out.println(response.getItems());
            System.out.println(response.getTook());
            System.out.println("===============操作结果==============");
        }catch (Exception e){
            System.out.println(e);
        }finally {
            esClient.close();
        }
    }
}
